package com.yjd.bi.first.service.impl;

import com.alibaba.fastjson.JSON;
import com.yjd.bi.first.dao.IInvestFirstDao;
import com.yjd.bi.first.model.InvestFirstModel;
import com.yjd.bi.first.service.IInvestFirstService;
import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.comm.util.FrameUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <b>description</b>：首次投资记录（投标和债权转让）业务实现<br>
 * <b>time</b>：2017-04-01 16:50:24 <br>
 * <b>author</b>：  carl
 */
@Service("investFirstService")
public class InvestFirstServiceImpl extends BaseServiceImpl implements IInvestFirstService {

    @Resource
    private IInvestFirstDao investFirstDao;

    /**
     * 插入
     *
     * @param model
     * @return
     * @throws Exception
     */
    public InvestFirstModel insert(InvestFirstModel model) throws Exception {
        return this.investFirstDao.insertModel(model, true);
    }

    /**
     * 更新
     *
     * @param model
     * @return
     * @throws Exception
     */
    public int update(InvestFirstModel model) throws Exception {
        return this.investFirstDao.updateModel(model, true);
    }

    /**
     * 根据id删除
     *
     * @param user_id
     * @return
     * @throws Exception
     */
    public int delete(long user_id) throws Exception {
        Map<Object, Object> paramMap = new HashMap<Object, Object>();
        paramMap.put("user_id", user_id);
        return this.investFirstDao.deleteModel(paramMap, true);
    }

    @Override
    public void generateInvestFirst(Long startTime, Long endTime) throws Exception {
        if (startTime == null || endTime == null) {
            FrameUtil.throwBaseException1("请求参数异常");
        }

        Map param = new HashMap();
        param.put("starttime", startTime);
        param.put("endtime", endTime);

        List<InvestFirstModel> firstInvestList = this.investFirstDao.getInvestFirstList(param);
        if (firstInvestList == null || firstInvestList.size() == 0) {
            logger.info("当前日期未查询到当天首次投资的用户，参数：" + JSON.toJSONString(param));
        }

        List<InvestFirstModel> firstCreditorList = this.investFirstDao.getCreditorTransferFirstList(param);
        if (firstCreditorList == null || firstCreditorList.size() == 0) {
            logger.info("当前日期未查询到当天首次购买债权的用户，参数：" + JSON.toJSONString(param));
        }

        List<InvestFirstModel> firstList = new ArrayList<InvestFirstModel>();
        Map<Long, InvestFirstModel> existsUser = new HashMap<Long, InvestFirstModel>();

        if (firstInvestList != null && firstCreditorList != null) {
            for (InvestFirstModel model : firstInvestList) {
                existsUser.put(model.getUser_id(), model);
            }

            for (InvestFirstModel creditorModel : firstCreditorList) {
                if (existsUser.containsKey(creditorModel.getUser_id())) {
                    InvestFirstModel investModel = existsUser.get(creditorModel.getUser_id());
                    if (investModel.getAddtime() != null && creditorModel.getAddtime() != null) {
                        if (investModel.getAddtime() > creditorModel.getAddtime()) {
                            existsUser.remove(investModel.getUser_id());
                            existsUser.put(creditorModel.getUser_id(), creditorModel);
                        }
                    }
                } else {
                    existsUser.put(creditorModel.getUser_id(), creditorModel);
                }
            }

        } else if (firstInvestList != null && firstCreditorList == null) {
            for (InvestFirstModel model : firstInvestList) {
                existsUser.put(model.getUser_id(), model);
            }
        } else if (firstInvestList == null && firstCreditorList != null) {
            for (InvestFirstModel creditorModel : firstCreditorList) {
                existsUser.put(creditorModel.getUser_id(), creditorModel);
            }
        }

        if (startTime >= 1440950400 && startTime <= 1467302400) {
            //小钱包于2015年9月初上线2016年7月已经下线，统计时间超过的就无需统计
            List<InvestFirstModel> firstWalList = this.investFirstDao.getWalFirstList(param);

            if (firstWalList == null || firstWalList.size() == 0) {
                logger.info("当前日期未查询到当天首次投资小钱包的用户，参数：" + JSON.toJSONString(param));
            } else {
                for (InvestFirstModel walModel : firstWalList) {
                    if (existsUser.containsKey(walModel.getUser_id())) {
                        InvestFirstModel investModel = existsUser.get(walModel.getUser_id());
                        if (investModel.getAddtime() != null && walModel.getAddtime() != null) {
                            if (investModel.getAddtime() > walModel.getAddtime()) {
                                existsUser.remove(walModel.getUser_id());
                                existsUser.put(walModel.getUser_id(), walModel);
                            }
                        }
                    } else {
                        existsUser.put(walModel.getUser_id(), walModel);
                    }
                }

            }
        }


        if (existsUser != null && existsUser.size() > 0) {
            List<Long> userIds = new ArrayList<Long>();
            Set<Long> set = existsUser.keySet();
            for (Iterator<Long> it = set.iterator(); it.hasNext(); ) {
                userIds.add(it.next());
            }
            Map<Long, InvestFirstModel> existsMap = this.investFirstDao.getModelMapByIds(userIds, false);
            if (existsMap != null) {
                for (Iterator<Long> eit = existsMap.keySet().iterator(); eit.hasNext(); ) {
                    existsUser.remove(eit.next());
                }
            }
        }

        if (existsUser != null && existsUser.size() > 0) {
            for (Iterator<Long> uit = existsUser.keySet().iterator(); uit.hasNext(); ) {
                firstList.add(existsUser.get(uit.next()));
            }
        }
        if (firstList.size() == 0) {
            logger.info("当前日期查询到当天首投资且过滤后没有相关用户，参数：" + JSON.toJSONString(param));
            return;
        }

        this.investFirstDao.insertBatch(firstList, true);

    }

    @Override
    public Double getFirstInvestUseTimes(Map param) throws Exception {
        return this.investFirstDao.getFirstInvestUseTimes(param);
    }

    @Override
    public IBaseDao getBaseDao() {
        return this.investFirstDao;
    }

}
